package com.aqgj.Attachment.web;

import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.service.AttachmentManager;
import com.aqgj.User.bean.User;
import com.aqgj.util.GenericsUtils;
import com.aqgj.util.ImageUtil;
import com.aqgj.util.JsonWrapper;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


@Controller
@RequestMapping("fileupload")
public class AttachmentAction {
    @Autowired
    private AttachmentManager attachmentManager;
    private static final Logger log = LogManager.getLogger(AttachmentAction.class);

    /**
     * 保存上传文件.
     * @param file       文件
     * @param workItem    标识
     * @param session   用户session
     * @param isSaveDisk 是否写入服务器
     */
    @RequestMapping("saveUnique")
    public void saveUnique(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request, HttpSession session, String businessId,String workItem, Boolean isSaveDisk) {
         Attachment attachment = new Attachment();
         User user= (User) session.getAttribute("userInfo");//后台当前用户
        try {
            attachment.setFileBody(file.getBytes());
            attachment.setFileSize(String.valueOf(file.getSize()));
            attachment.setFileType(file.getContentType());
            attachment.setFileName(file.getOriginalFilename());
            attachment.setWorkItem(workItem);
            attachment.setUploadTime(new Date());
            if (user != null){
                attachment.setUploader(user.getId());
                attachment.setUploaderName(user.getAccount());
            }
            attachment.setBusinessId(businessId);//=======================业务id=======================
            String id = attachmentManager.saveAttachment(attachment);
            attachment.setFilePath(id);
            attachmentManager.saveAttachment(attachment);
            if (isSaveDisk) {
                File file1= getRealPath(request);
                file.transferTo(new File(file1.getPath() + file.getOriginalFilename()));
            }
        } catch (IOException e) {
            e.printStackTrace();
           log.info("保存失败,原因为:"+e.getMessage().toString());
        }
    }


    /**
     * 保存上传水印的图片.
     * @param file      文件
     * @param workItem  标识
     * @param session 用户session
     * @param isSaveDisk 是否写入服务器
     */
    @RequestMapping("saveMarkImg")
    public void saveMarkImg(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request, HttpSession session,String businessId, String workItem,Boolean isSaveDisk,String markText) {
        CommonsMultipartFile cf= (CommonsMultipartFile)file;
        DiskFileItem fi = (DiskFileItem)cf.getFileItem();
        File f = fi.getStoreLocation();
        InputStream rfile = ImageUtil.markImageByText(markText, f, -45);
        Attachment attachment = new Attachment();
        try {
            byte[] data = new byte[rfile.available()];
            rfile.read(data);
            attachment.setFileBody(data);
            attachment.setFileSize(String.valueOf(file.getSize()));
            attachment.setFileType(file.getContentType());
            attachment.setFileName(file.getOriginalFilename());
            attachment.setWorkItem(workItem);
            attachment.setUploadTime(new Date());
            User user= (User) session.getAttribute("userInfo");
            if (user != null){
                attachment.setUploader(user.getId());
                attachment.setUploaderName(user.getAccount());
            }
            attachment.setBusinessId(businessId);
            String id = attachmentManager.saveAttachment(attachment);
            attachment.setFilePath(id);
            attachmentManager.saveAttachment(attachment);
            if (isSaveDisk) {
                File file1= getRealPath(request);
                file.transferTo(new File(file1.getPath() + file.getOriginalFilename()));
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.info("保存失败,原因为:"+e.getMessage().toString());
        }
    }

    /**
     * 下载文件.
     * @param path    文件路径
     * @param fileName 文件名
     * @throws Exception
     */
    @RequestMapping("downloadByFilePath")
    public void downloadByFilePath(HttpServletRequest request, HttpServletResponse response, String path, String fileName){
        Attachment attachment = attachmentManager.getAttchementByPath(path);
        if (attachment == null) {
            log.info("图片请求失败,原因为:文件不存在");
            return;
        }
        InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(attachment.getFileBody()));
        BufferedOutputStream bos = null;
        try {
            //准备输出
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.addHeader("Content-Length", "" + inputStream.available());
            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(attachment.getFileBody());
            bos.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据业务id获取文件集合.
     * @param businessId 业务id
     * @return
     */
    @RequestMapping("attachmentList")
    @ResponseBody
    public void attachmentList(HttpServletResponse response,String businessId) {
        if (!GenericsUtils.isEmpty(businessId)) {
            List<Attachment> list = attachmentManager.getAttachmentByBusinessId(businessId);
            String str = "{\"success\":\"true\",\"data\":[";
            for (int i = 0; i < list.size(); i++){
                Attachment attachment =list.get(i);
                String relativePath = "";
                str = str + (i == 0 ? "{" : ",{");
                str = str + "\"id\":\"" + attachment.getId() + "\",\"name\":\"" + attachment.getFileName() +
                        "\",\"filePath\":\"" + attachment.getFilePath() + "\",\"relativePath\":\"" + relativePath +
                        "\",\"uploadTime\":\"" + attachment.getUploadTime() + "\"" +
                        ",\"workItem\":\"" + attachment.getWorkItem() + "\"," + "\"fileSize\":\"" +
                        attachment.getFileSize()  + "\"," + "\"fileBody\":\"" + attachment.getFileBody() + "\"}";
            }
            str = str + "]}";
            try {
                response.getWriter().print(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     }
    /**
     * 根据业务id获取文件集合.
     * @param businessId 业务id
     * @return 照片集合
     */
    @RequestMapping("getAttachmentListByBusinessId")
    @ResponseBody
    public  HashMap<String, Object>  getAttachmentListByBusinessId (HttpServletResponse response,String businessId)throws UnsupportedEncodingException {

        if (!GenericsUtils.isEmpty(businessId)) {
            HashMap<String, Object> wapper = new HashMap<>();

//            HashMap<String, Object> backList = new HashMap<>();
            List<Object> objectList= new ArrayList();
            List<Attachment> list = attachmentManager.getAttachmentByBusinessId(businessId);
            final Base64.Decoder decoder = Base64.getDecoder();
            final Base64.Encoder encoder = Base64.getEncoder();
            for(Attachment attachment:list){
                HashMap<String, Object> backList = new HashMap<>();
                backList.put("id",attachment.getId());
                backList.put("name", attachment.getFileName());
                backList.put("filePath",attachment.getFilePath());
                backList.put("uploadTime",attachment.getUploadTime());
                backList.put("workItem",attachment.getWorkItem());
                backList.put("filePath",attachment.getFilePath());
                backList.put("fileSize",attachment.getFileSize());
                backList.put("fileBody",new String(decoder.decode(encoder.encodeToString(attachment.getFileBody())), "UTF-8"));
                objectList.add(backList);
            }
            wapper.put("success", Boolean.valueOf(true));
            wapper.put("data",objectList);
            return wapper;
//            attachmentElement += "{\"img\":\"data:"+ attachment.getFileType() + ";base64," + getFileBody(attachment.getFileBody())+ "\",\"text\":\""+routeAttachment.getViewContent()+"\"}";

        }else{
            return JsonWrapper.failureWrapperMsg("业务id为空，请重新输入!");
        }
    }
     //获取服务器上传地址
     private File getRealPath(HttpServletRequest request){
         String path = request.getServletContext().getRealPath("/upload/");
         File file1 = new File(path);
         if (!file1.exists()) {
             file1.mkdirs();
         }
         return file1;
     }

    /**
     * 直接保存图片，采用base64直接传输存储二进制
     * @param attachment
     * @param session
     * @return
     */
    @RequestMapping("saveInfo")
    @ResponseBody
    public HashMap<String, Object> saveInfo(Attachment attachment, HttpSession session) throws UnsupportedEncodingException {
        User user= (User) session.getAttribute("userInfo");
        attachment.setUploader(user.getId());
        attachment.setUploaderName(user.getName());
        attachment.setUploadTime(new Date());
        String id = attachmentManager.saveAttachment(attachment);
        return JsonWrapper.successWrapper(attachment.getId());
    }
    /**
     * 修改图片，采用base64直接传输存储二进制
     * @param attachment
     * @param session
     * @return
     */
    @RequestMapping("update")
    @ResponseBody
    public HashMap<String, Object> update(Attachment attachment, String fileBody,HttpSession session) throws UnsupportedEncodingException {
        User user= (User) session.getAttribute("userInfo");
        if(attachment.getId()==null||attachment.getId().isEmpty()){ return JsonWrapper.failureWrapperMsg("获取图片id失败");}
        Attachment attachment1=attachmentManager.get(attachment.getId());
        if(attachment1==null){return JsonWrapper.failureWrapperMsg("请传入正确照片id");}
        attachment1.setUploader(user.getId());
        attachment1.setUploaderName(user.getName());
        attachment1.setUploadTime(new Date());
        String[] arrays = fileBody.split("\\,");
        if(arrays.length<3){
            return JsonWrapper.failureWrapperMsg("照片参数错误，添加失败!");
        }
        attachment1.setFileType(arrays[0].split(":")[1].split(";")[0]);
        attachment1.setFileName(arrays[2]);
//        String[] bodyInfos = bodyInfo.split(",");
        try {
            byte[] b = new BASE64Decoder().decodeBuffer(arrays[1]);
            for (int j = 0; j < b.length; ++j) {
                if (b[j] < 0) {
                    // 调整异常数据
                    b[j] += 256;
                }
            }
            attachment1.setFileBody(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        attachmentManager.save(attachment1);
        return JsonWrapper.successWrapper(attachment1.getId());
    }

    /**
     * 通过id删除图片
     * @param id 图片id
     * @return
     */
    @RequestMapping("deleteById")
    @ResponseBody
    public HashMap<String, Object> deleteById(String id) {
        attachmentManager.delete(id);
        return JsonWrapper.successWrapper();
    }
}

